<template>
  <div class="dispatch-page">
    <!-- 添加自动派单按钮区域 -->
    <div class="auto-dispatch-section">
      <el-button
        type="success"
        :loading="autoDispatchLoading"
        @click="handleAutoDispatch"
      >
        {{ autoDispatchLoading ? '自动派单中...' : '自动派单' }}
      </el-button>
      <el-alert
        v-if="autoDispatchResult"
        :type="autoDispatchResult.success ? 'success' : 'error'"
        :title="autoDispatchResult.message"
        show-icon
        closable
        @close="autoDispatchResult = null"
        style="margin-top: 10px; margin-bottom: 10px;"
      />
    </div>

    <el-card class="table-card">
      <el-table :data="workOrderList" v-loading="loading" border>
        <el-table-column prop="title" label="工单标题" min-width="150" />
        <el-table-column prop="customerName" label="客户姓名" min-width="100" />
        <el-table-column prop="customerPhone" label="联系电话" min-width="120" />
        <el-table-column prop="address" label="地址" min-width="250" />
        <el-table-column prop="createTime" label="下单时间" min-width="250" />
        <el-table-column prop="des" label="工单描述" min-width="300" />
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openDispatchDialog(row)">
              派单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNo"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 派单对话框 -->
    <el-dialog
      title="工单派单"
      v-model="dispatchDialogVisible"
      width="500px"
      @close="handleCloseDispatchDialog"
    >
      <el-form
        ref="dispatchFormRef"
        :model="dispatchForm"
        :rules="dispatchRules"
        label-width="100px"
      >
        <el-form-item label="工单标题">
          <el-input v-model="currentWorkOrder.title" disabled />
        </el-form-item>

        <el-form-item label="接单员" prop="receiverId">
          <el-select
            v-model="dispatchForm.receiverId"
            placeholder="请选择接单员"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="staff in staffList"
              :key="staff.userId"
              :label="staff.userName"
              :value="staff.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="handleCloseDispatchDialog">取消</el-button>
        <el-button type="primary" @click="submitDispatch" :loading="dispatchLoading">
          确定派单
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onActivated } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getUnassignedWorkOrders,
  dispatchWorkOrder,
  autoDispatchWorkOrder // 引入自动派单接口
} from '@/api/workOrder'
import { getRoleUsers } from '@/api/permission'

const searchForm = reactive({
  customerPhone: ''
})

// 分页参数
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 数据列表和状态
const workOrderList = ref([])
const loading = ref(false)

// 自动派单相关
const autoDispatchLoading = ref(false)
const autoDispatchResult = ref(null)

// 派单相关
const dispatchDialogVisible = ref(false)
const dispatchFormRef = ref()
const dispatchLoading = ref(false)

const currentWorkOrder = ref({})
const dispatchForm = reactive({
  receiverId: '',
  remark: ''
})

const dispatchRules = {
  receiverId: [
    { required: true, message: '请选择接单员', trigger: 'change' }
  ]
}

// 员工列表
const staffList = ref([])

// 获取未派单工单列表
const fetchUnassignedWorkOrders = async () => {
  loading.value = true
  try {
    // 构造查询参数对象，将搜索条件和分页参数合并
    const params = {
      ...searchForm,
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize
    }

    const response = await getUnassignedWorkOrders(params)

    // 根据实际返回结构调整
    if (response && response.data) {
      workOrderList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      workOrderList.value = []
      pagination.total = 0
    }
  } catch (error) {
    ElMessage.error('获取未派单工单列表失败: ' + (error.message || '未知错误'))
    workOrderList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 查询员工列表（角色为员工的用户）
const fetchStaffList = async () => {
  try {
    const response = await getRoleUsers(3)
    // 根据实际返回结构调整
    if (response && response.data) {
      staffList.value = Array.isArray(response.data) ? response.data : []
    } else if (Array.isArray(response)) {
      staffList.value = response
    } else {
      staffList.value = []
    }
  } catch (error) {
    ElMessage.error('获取员工列表失败: ' + (error.message || '未知错误'))
    staffList.value = []
  }
}

// 搜索
const searchUnassignedOrders = () => {
  pagination.pageNo = 1
  fetchUnassignedWorkOrders()
}

// 重置搜索
const resetSearch = () => {
  // 重置搜索表单
  searchForm.customerPhone = ''

  // 重置分页并重新加载数据
  pagination.pageNo = 1
  fetchUnassignedWorkOrders()
}

// 分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchUnassignedWorkOrders()
}

const handleCurrentChange = (val) => {
  pagination.pageNo = val
  fetchUnassignedWorkOrders()
}

// 打开派单对话框
const openDispatchDialog = (row) => {
  currentWorkOrder.value = { ...row }
  dispatchDialogVisible.value = true
}

// 关闭派单对话框
const handleCloseDispatchDialog = () => {
  dispatchDialogVisible.value = false
  dispatchForm.receiverId = ''
  dispatchForm.remark = ''
  if (dispatchFormRef.value) {
    dispatchFormRef.value.resetFields()
  }
}

// 提交派单
const submitDispatch = async () => {
  await dispatchFormRef.value.validate(async (valid) => {
    if (!valid) return

    dispatchLoading.value = true
    try {
      const dispatchData = {
        workOrderId: currentWorkOrder.value.id,
        employeeId: dispatchForm.receiverId,  // 修改为后端期望的字段名
        remark: dispatchForm.remark
      }

      await dispatchWorkOrder(dispatchData)
      ElMessage.success('派单成功')
      handleCloseDispatchDialog()
      fetchUnassignedWorkOrders() // 刷新列表
    } catch (error) {
      ElMessage.error('派单失败: ' + (error.message || '未知错误'))
    } finally {
      dispatchLoading.value = false
    }
  })
}

// 自动派单功能
const handleAutoDispatch = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要执行自动派单吗？系统将自动为未派单的工单分配接单员。',
      '自动派单确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    autoDispatchLoading.value = true
    autoDispatchResult.value = null

    // 调用自动派单接口
    const response = await autoDispatchWorkOrder({})

    if (response && response.data) {
      const { successCount, failCount, message } = response.data
      autoDispatchResult.value = {
        success: true,
        message: `自动派单完成：成功${successCount}单，失败${failCount}单`
      }
    } else {
      autoDispatchResult.value = {
        success: true,
        message: '自动派单执行完成'
      }
    }

    // 刷新工单列表
    fetchUnassignedWorkOrders()
  } catch (error) {
    if (error !== 'cancel') {
      autoDispatchResult.value = {
        success: false,
        message: '自动派单执行失败: ' + (error.message || '未知错误')
      }
      ElMessage.error('自动派单执行失败: ' + (error.message || '未知错误'))
    }
  } finally {
    autoDispatchLoading.value = false
  }
}

// 初始化数据
const initPageData = async () => {
  await Promise.all([
    fetchStaffList()
  ])
  fetchUnassignedWorkOrders()
}

onMounted(() => {
  initPageData()
})

// 处理keep-alive缓存页面重新激活的情况
onActivated(() => {
  initPageData()
})
</script>

<style scoped>
.dispatch-page {
  padding: 20px;
}

.auto-dispatch-section {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
